<template>
	<div class="sw_upload_container">
		<el-upload class="uploader" :action="uploadAction" :accept="uploadAccept" :autoUpload="!clip" v-bind="uploadConfig" />
		<div class="uploadbox" :style="uploadSize">
			<el-button v-if="!imageUrl" class="added" icon="el-icon-plus" @click="handleAgainUpload()"></el-button>
			<el-image v-else ref="image" :src="imageUrl" fit="contain" :preview-src-list="[imageUrl]"></el-image>
			<el-button-group v-if="!!imageUrl">
				<el-button type="text" icon="el-icon-edit" @click="handleAgainUpload()"></el-button>
				<el-button type="text" icon="el-icon-search" @click="handlePreviewUpload()"></el-button>
				<el-button type="text" icon="el-icon-delete" @click="handleDeleteUpload()"></el-button>
			</el-button-group>
		</div>
		<template v-if="!!clip">
			<sw-image-cropper v-model="cropperDialog" :type="`[${cropperRatio}]`" :file="uploadFile" @finish="handleCropperFinish" />
		</template>
	</div>
</template>

<script>
import { mapActions } from 'vuex';
import emitter from 'element-ui/src/mixins/emitter';
const baseUrl = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
export default {
	mixins: [emitter],
	name: 'swImageUploader',
	props: {
		value: { type: String, default: '' },
		type: { type: String, default: '1' },
		size: { type: String, default: '150' },
		clip: { type: Boolean, default: false },
		ratio: { type: String, default: '1:1' },
		accept: { type: String, default: 'png' }
	},
	data() {
		let Authorization = this.$session.get('token');
		let uploadParams = { showType: '1', type: '1' };
		return {
			imageId: this.value,
			imageUrl: '',
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				autoUpload: false,
				data: uploadParams,
				showFileList: false,
				headers: { Authorization },
				onChange: this.handleUploadChange,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload
			},
			cropperDialog: false,
			uploadFile: null,
			uploadFiles: []
		};
	},
	computed: {
		uploadAction() {
			return `${baseUrl}/tbSysAttachment/upload`;
		},
		uploadAccept() {
			let acceptArr = this.accept.split(',');
			return acceptArr.map((n) => `.${n}`).join();
		},
		uploadSize() {
			let size = parseInt(this.size);
			let ratios = this.ratio.split(':');
			let ratioNumber = parseInt(ratios[1]) / parseInt(ratios[0]);
			return { width: `${size}px`, height: `${size * ratioNumber}px` };
		},
		cropperRatio() {
			return this.ratio.split(':').join(',');
		}
	},
	watch: {
		value(val) {
			this.imageId = val;
		},
		imageId: {
			async handler(val) {
				this.$emit('input', val);
				this.dispatch('ElFormItem', 'el.form.change', [val]);
				if (!val) return false;
				this.imageUrl = await this.initializeImage(val);
			},
			immediate: true
		}
	},
	methods: {
		...mapActions(['getFileUrl']),
		//初始化图片
		async initializeImage(id) {
			let imgPath = await this.getFileUrl(id);
			return imgPath?.replaceIP() || '';
		},
		//上传变化
		async handleUploadChange(file, fileList) {
			this.uploadFiles = fileList;
			if (!this.clip) return false;
			if (file.status === 'ready') {
				this.cropperDialog = true;
				this.uploadFile = file.raw;
			}
		},
		//上传前设置
		handleBeforeUpload(file) {
			let acceptArr = this.accept.split(',');
			let suffix = file.name.split('.').pop();
			let isExceed = file.size < 2 * 1024 * 1024;
			let isImage = acceptArr.some((n) => n === suffix);
			if (!isExceed) {
				this.$message.error(`您上传的图片大小超过2MB`);
				return false;
			}
			if (!isImage) {
				this.$message.error(`您上传的图片类型不是 ${this.accept}`);
				return false;
			}
		},
		//图片裁剪完成
		handleCropperFinish(file) {
			this.cropperDialog = false;
			if (!file) {
				this.$refs['upload'].clearFiles();
			} else {
				this.uploadFiles[0].raw = file;
				this.$refs['upload'].submit();
			}
		},
		//上传成功
		handleUploadSuccess(res, file, fileList) {
			this.$refs['upload'].clearFiles();
			if (res.code === '0') {
				this.imageId = this.$detailData(res.data).id;
			}
		},
		//重新上传
		handleAgainUpload() {
			this.$refs['upload'].$refs['upload-inner'].handleClick();
		},
		//预览上传
		handlePreviewUpload() {
			this.$refs['image'].clickHandler();
		},
		//删除上传
		handleDeleteUpload() {
			this.imageId = '';
			this.imageUrl = '';
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_upload_container {
	position: relative;
	overflow: hidden;
	.uploader {
		position: absolute;
		opacity: 0;
		z-index: 1;
	}
	.uploadbox {
		position: relative;
		z-index: 2;
	}
	.el-image {
		position: relative;
		width: 100%;
		height: 100%;
		border-radius: 4px;
		background-color: var(--primary-background-plain-disabled);
		z-index: 2;
	}
	.el-button.added {
		position: relative;
		width: 100%;
		height: 100%;
		padding: 0;
		font-size: 24px;
		border-style: dashed;
	}
	.el-button-group {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 3;
		width: 100%;
		height: 100%;
		border-radius: 4px;
		display: none;
		.el-button {
			font-size: 18px;
			padding: 0;
			color: #fff;
		}
	}
	&:hover .el-button-group {
		display: flex;
		align-items: center;
		justify-content: space-around;
		background-color: rgba(0, 0, 0, 0.5);
	}
}
</style>